package com.betterjr.modules.risk.loan.data;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.betterjr.common.utils.Collections3;
import com.betterjr.modules.risk.loan.dao.CalculateChargeLinkChain;
import com.betterjr.modules.risk.loan.entity.LoanProjectCharge;

public class CalculateChargeFactory {

    private final static int DEFAULT_SIZE_FACTORY = 4;

    private static List<CalculateChargeLinkChain> chargetChain = new ArrayList<>(DEFAULT_SIZE_FACTORY);

    static {

        chargetChain.add(new NormalCalculate());
        chargetChain.add(new MultiplyFirstCalculate());

    }

    public static void addCalculate(CalculateChargeLinkChain calculate) {

        if (chargetChain != null && !chargetChain.contains(calculate)) {
            chargetChain.add(calculate);
        }
    }

    public static void removeCalculate(CalculateChargeLinkChain calculate) {

        if (chargetChain != null && !chargetChain.contains(calculate)) {
            chargetChain.remove(calculate);
        }

    }

    public static BigDecimal invoke(LoanProjectCharge charge) {

        if (charge != null && !Collections3.isEmpty(chargetChain)) {

            List<BigDecimal> set = new ArrayList<BigDecimal>(chargetChain.size());
            for (CalculateChargeLinkChain chain : chargetChain) {
                set.add(chain.invokeChain(charge));
            }

            Collections.sort(set);

            return Collections3.getLast(set).setScale(2, BigDecimal.ROUND_HALF_UP);

        }

        return new BigDecimal(0);

    }

}
